<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: guosheng1987@126.com 
// +----------------------------------------------------------------------
namespace plugins\crawler\service; 

use think\File;
use think\Db;
use app\user\model\AssetModel;

use plugins\crawler\model\CrawlerSiteModel;
use plugins\crawler\model\CrawlerUrlModel;
use plugins\crawler\model\CrawlerRuleModel;
use plugins\crawler\model\CrawlerCollectionModel;

use app\portal\model\PortalPostModel;
use app\portal\model\PortalCategoryModel;

class CrawlerService 
{   
    /**  被重载的数据保存在此  */
    private $data = array();

    public function __set($name, $value) 
    {
        $this->data[$name] = $value;
    }

    public function __get($name) 
    {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }
    }

    /**
     * save file to local from curl stream
     * @access public
     * @param  Resource $stream file stream
     * @param  String $remotePath 
     * @return Array 
     */
    public function saveLocalFile($stream, $remotePath)
    {
        $fileType = $this->fileType;
        
        @set_time_limit(24 * 60 * 60);
        $cleanupTargetDir = false; // Remove old files
        $maxFileAge       = 5 * 3600; // Temp file age in seconds
    
        if (empty($app) || !file_exists(APP_PATH . $app)) {
            $app = 'default';
        }

        $remotePathInfo = pathinfo($remotePath);

        //$fileImage    = $this->request->file($this->formName);
        $originalName = $remotePathInfo['basename'];
        $strFileExtension = $remotePathInfo['extension'];

        //default "upload" . DS;
        $strWebPath = "";
        $strId      = '';
        $strDate    = date('Ymd');

        $user = Db::name("user")->where('user_type', '1')->find();
        //default admin upload
        $userId    = $user['id'];

        $fileSaveName    = (empty($app) ? '' : $app . '/') . $strDate . '/' . md5(uniqid()) . "." . $strFileExtension;
        $strSaveFilePath = CMF_ROOT. './public/upload/' . $fileSaveName; //TODO 测试 windows 下
        $strSaveFileDir  = dirname($strSaveFilePath);
        
        // 文件上传到临时目录，然后根据md5 判断是否存在文件，如果存在文件则删除临时目录文件，否则将文件移动到 上传目录
        if (!file_exists($strSaveFileDir)) {
            mkdir($strSaveFileDir, 0777, true);
        }

        // save file
        @file_put_contents($strSaveFilePath, $stream);

        $fileImage = new File($strSaveFilePath, 'r');
        $arrInfo   = [
            "name"     => $originalName,
            "type"     => $fileImage->getMime(),
            "tmp_name" => $strSaveFilePath,
            "error"    => 0,
            "size"     => $fileImage->getSize(),
        ];

        $fileImage->setSaveName($fileSaveName);
        $fileImage->setUploadInfo($arrInfo);

      
        //  $url=$first['url'];
        $storageSetting = cmf_get_cmf_settings('storage');
        $qiniuSetting   = $storageSetting['Qiniu']['setting'];
        //$url=preg_replace('/^https/', $qiniu_setting['protocol'], $url);
        //$url=preg_replace('/^http/', $qiniu_setting['protocol'], $url);

        $arrInfo = [];
        if (config('FILE_UPLOAD_TYPE') == 'Qiniu' && $qiniuSetting['enable_picture_protect']) {
            //todo  qiniu code ...
            // $previewUrl = $url.$qiniuSetting['style_separator'].$qiniuSetting['styles']['thumbnail300x300'];
            // $url= $url.$qiniuSetting['style_separator'].$qiniuSetting['styles']['watermark'];
        } else {

            if (empty($fileImage)) {
                $this->error = $fileImage->getError();
                return false;
            } else {
                $arrInfo["user_id"]     = $userId;
                $arrInfo["file_size"]   = $fileImage->getSize();
                $arrInfo["create_time"] = time();
                $arrInfo["file_md5"]    = md5_file($strSaveFilePath);
                $arrInfo["file_sha1"]   = sha1_file($strSaveFilePath);
                $arrInfo["file_key"]    = $arrInfo["file_md5"] . md5($arrInfo["file_sha1"]);
                $arrInfo["filename"]    = $fileImage->getInfo("name");
                $arrInfo["file_path"]   = $strWebPath . $fileSaveName;
                $arrInfo["suffix"]      = $fileImage->getExtension();
            }

        }

        //关闭文件对象
        $fileImage = null;
        //检查文件是否已经存在
        $assetModel = new AssetModel();
        $objAsset   = $assetModel->where(["user_id" => $userId, "file_key" => $arrInfo["file_key"]])->find();

        $storage = cmf_get_option('storage');

        if (empty($storage['type'])) {
            $storage['type'] = 'Local';
        }

        $needUploadToRemoteStorage = false;//是否要上传到云存储
        if ($objAsset && $storage['type'] =='Local') {
            $arrAsset = $objAsset->toArray();
            
            //$arrInfo["url"] = $this->request->domain() . $arrAsset["file_path"];
            $arrInfo["file_path"] = $arrAsset["file_path"];
            if (file_exists(CMF_ROOT. './public/upload/' . $arrInfo["file_path"])) {
                @unlink($strSaveFilePath); // 删除已经上传的文件
            } else {
                $oldFileDir = dirname(CMF_ROOT. './public/upload/' . $arrInfo["file_path"]);

                if (!file_exists($oldFileDir)) {
                    mkdir($oldFileDir, 0777, true);
                }

                @rename($strSaveFilePath, CMF_ROOT. './public/upload/' . $arrInfo["file_path"]);
            }

        } else {
            $needUploadToRemoteStorage = true;
            $assetModel->data($arrInfo)->allowField(true)->save();
        }
    
        return [
            'filepath'    => $arrInfo["file_path"],
            "name"        => $arrInfo["filename"],
            'id'          => $strId,
            'preview_url' => cmf_get_root() . '/upload/' . $arrInfo["file_path"],
            'url'         => cmf_get_root() . '/upload/' . $arrInfo["file_path"],
        ];
    }

    /**
     * 根据栏目id获取文章栏目名
     * @access public
     * @param  Int $categoryId 
     * @return String $categoryName
     */
    public function getPortalCategoryNameById($categoryId)
    {
        $portalCategoryModel = new PortalCategoryModel();
        $categoryName = $portalCategoryModel->find($categoryId)->name;
        
        return $categoryName;
    }

    /**
     * delete duplicate from portal and crawler_collection table 
     * @access public
     * @param  Int $collectionId 
     * @return void
     */
    public function deletePortal($collectionId)
    {
        $postId = Db::name('crawler_collection')
            ->where(['crawler_site_id' => $this->site->id, 'collection_id' => $collectionId])
            ->value('post_id');

        if($postId)
        {
            Db::name('portal_post')
                ->where(['id' => ['in', $postId]])
                ->delete();
            Db::name('portal_category_post')
                ->where(['post_id' => ['in', $postId]])
                ->delete();
            Db::name('portal_tag_post')
                ->where(['post_id' => ['in', $postId]])
                ->delete();
        }
        
    }
    
    /**
     * 保存文章和和相关数据
     * @access public
     * @param  Int $categoryId 
     * @param  String $title  
     * @param  String $excerpt 
     * @param  String $content 
     * @return void|int
     */
    public function addPortalAndTag($categoryId, $title, $excerpt ,$content, $thumbnail='')
    {
        
        $data = [
            'user_id'       => '1',
            'categories'    => $categoryId,
            'post_title'    => $title,
            'post_keywords' => '',
            'post_source'   => '',
            'post_excerpt'  => $excerpt,
            'more' => [
                'thumbnail' => $thumbnail,
                'template'  => '',
            ],
            'published_time' => date('Y-m-d H:i:s'),
            'post_status'    => '1',
            'post_content'   => $content,
        ];

        $portalPostModel = new PortalPostModel();
        
        $portalPostModel->allowField(true)->data($data, true)->isUpdate(false)->save();
        
        $categories = $data['categories'];

        if ($categories) {
            $categories = explode(',', $categories);
        }

        $portalPostModel->categories()->save($categories);

        $data['post_keywords'] = str_replace('，', ',', $data['post_keywords']);

        $keywords = explode(',', $data['post_keywords']);

        $portalPostModel->addTags($keywords, $portalPostModel->id);

        return $portalPostModel->id;
    }

    /**
     * 采集结果 插入采集数据表 
     * @access public
     * @param  Int $postId 
     * @param  Array $collection 
     * @return void
     */
    public function addCrawlerCollection($postId, $collection)
    {
        $time = time();

        $data = [];

        $data['crawler_site_id'] = $this->site->id;
        $data['crawler_url_id']  = $this->url->id;
        $data['crawler_rule_id'] = $this->url->crawler_rule_id;
        $data['collection_id']   = $collection['collection_id'];
        $data['post_id']         = $postId;
        $data['title']           = $collection['title'];
        $data['content']         = $collection['content'];
        $data['data']            = json_encode($collection);
        $data['create_time']     = $time;

        
        $postId = Db::name('crawler_collection')
            ->where(['crawler_site_id' => $data['crawler_site_id'], 'collection_id' => $collection['collection_id']])
            ->delete();

        Db::name('crawler_collection')->insert($data);
        //Db::name('crawler_collection')->insert($data);
        
        //echo Db::table('crawler_collection')->getLastSql();

    }
}